﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;

namespace LostLib.Net
{
	public static class TcpClientExtensions
	{
		public static void NetworkTransfer(this TcpClient sourceClient, NetworkStream source, NetworkStream dest, int bufferSize)
		{
			byte[] buffer = new byte[bufferSize];
			int wait = 1;
			while (sourceClient.Client.Connected && sourceClient.Connected)
			{
				Thread.Sleep(wait);
				int read;
				do
				{
					read = source.Read(buffer, 0, bufferSize);
					if (read == 0)
						throw new SocketException();
					dest.Write(buffer, 0, read);
					wait = 1;
				} while (read > 0);

				// lock up to 16ms
				wait *= 2;
				if (wait > 16) wait = 16;
			}
		}

		public static void NetworkTransfer(this TcpClient sourceClient, NetworkStream source, NetworkStream dest, int bufferSize, Func<byte[], int, int, DBNull> transorm)
		{
			if (transorm == null)
			{
				sourceClient.NetworkTransfer(source, dest, bufferSize);
				return;
			}

			byte[] buffer = new byte[bufferSize];
			int wait = 1;
			while (sourceClient.Client.Connected && sourceClient.Connected)
			{
				Thread.Sleep(wait);
				int read;
				do
				{
					read = source.Read(buffer, 0, bufferSize);
					if (read == 0)
						throw new SocketException();
					transorm(buffer, 0, read);
					dest.Write(buffer, 0, read);
					wait = 1;
				} while (read > 0);

				// lock up to 16ms
				wait *= 2;
				if (wait > 16) wait = 16;
			}
		}
	}
}
